package com.starinside.wp.service.wx.impl;

import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.service.wx.VIPMpService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;

@Slf4j
public class VIPMpServiceImpl extends WxMpServiceImpl implements VIPMpService {

    @Override
    public void makeVIPAppIdValid(String forceAppId, String forceAppSecret) {

        log.debug("make VIPAppIdValid " + forceAppId + " ::: " + forceAppSecret);

        if(!switchover(forceAppId)){
            log.debug("can not switchover to appid " + forceAppId);
            //无法切换则增加新配置
            WxMpInMemoryConfigStorage configStorage = new WxMpInMemoryConfigStorage();

            configStorage.setAppId(forceAppId);
            configStorage.setSecret(forceAppSecret);

            log.debug("add mp config for " + forceAppId);
            addConfigStorage(forceAppId,configStorage);

            if(!switchover(forceAppId)){
                //再次切换失败则终止
                throw new BusinessException(ErrorCode.WX_AREA_MP_CONFIG_FAILED, "can not load mp config");
            }
        }
    }
}
